import time
import traceback
import logging
import os

from info_config import dbname
from info_config import prometheus_url
from info_config import time_interval
from info_config import wal_size_prometheus_metrics_name
from info_config import con_timeout
from tool_util import prometheus_push

from tool_util import create_conn
from tool_util import get_pg_wal_size
from tool_util import get_rds_resource_info



# Get the current script path
script_path = os.path.dirname(os.path.abspath(__file__))
log_file = os.path.join(script_path, "wal_size_monitor_all.log")

logging.basicConfig(
    filename=log_file,
    level=logging.INFO,
    format="%(asctime)s - %(levelname)s - %(message)s",
)


def pg_wal_size_monitor(pg_info):
    id = pg_info[0]
    name = pg_info[1]
    pg_host = pg_info[2].get("host")
    pg_port = pg_info[2].get("port")
    conn = create_conn(pg_host, pg_port, dbname, timeout=con_timeout)
    if conn is None:
        return
    try:
        wal_size = get_pg_wal_size(conn)
        if wal_size is not None:
            metric_data = f'{wal_size_prometheus_metrics_name}{{instanceId="{id}" ,resourceName="{name}"}} {wal_size}'
            prometheus_push(prometheus_url, metric_data)
    except Exception as e:
        traceback.print_exc


def wal_size_monitor_all(pg_info_list):
    for pg_info in pg_info_list:
        try:
            logging.info(f"start monitor {pg_info}")
            pg_wal_size_monitor(pg_info)
        except Exception as e:
            traceback.print_exc()


if __name__ == "__main__":
    pg_info_list = get_rds_resource_info()
    wal_size_monitor_all(pg_info_list)
